package java8;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/7/19 21:44
 */
public class TestListDistinct {

    public static void main(String[] args) {
        final List<String> list = new ArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            list.add("haha-" + i);
        }

        long time = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            removeDuplicate1(list);
        }
        long time1 = System.currentTimeMillis();
        System.out.println("time1:" + (time1 - time));

        for (int i = 0; i < 10000; i++) {
            removeDuplicate2(list);
        }
        long time2 = System.currentTimeMillis();
        System.out.println("time2:" + (time2 - time1));

        for (int i = 0; i < 10000; i++) {
            removeDuplicate3(list);
        }
        long time3 = System.currentTimeMillis();
        System.out.println("time3:" + (time3 - time2));

        for (int i = 0; i < 10000; i++) {
            removeDuplicate4(list);
        }
        long time4 = System.currentTimeMillis();
        System.out.println("time4:" + (time4 - time3));

    }

    private static void removeDuplicate1(List<String> list) {
        HashSet<String> set = new HashSet<>(list.size());
        set.addAll(list);
        list.clear();
        list.addAll(set);
    }

    private static void removeDuplicate2(List<String> list) {
        LinkedHashSet<String> set = new LinkedHashSet<>(list.size());
        set.addAll(list);
        list.clear();
        list.addAll(set);
    }

    private static void removeDuplicate3(List<String> list) {
        List<String> result = new ArrayList<>(list.size());
        for (String str : list) {
            if (!result.contains(str)) {
                result.add(str);
            }
        }
        list.clear();
        list.addAll(result);
    }

    private static void removeDuplicate4(List<String> list) {
        List<String> ls = list.parallelStream().distinct().collect(Collectors.toCollection(ArrayList::new));
        list.clear();
        list = ls;
    }
}
